<template>
  <div :style="{ paddingLeft: `${depth * 20}px`, marginBottom: '10px' }">
    <div class="comment" v-if="item.content">
      <strong>{{ item.username }}:</strong>
      <div class="comment-content"><span v-html="item.content"></span></div>
      <span class="comment-time">{{ item.time }}</span>
      <el-button size="mini" @click="toggleReply">回复</el-button>
      <el-button size="mini" @click="$emit('delete', item.id)">删除</el-button>
    </div>

    <!-- 回复框 -->
    <div v-if="isReplying" class="reply-container">
      <el-input
        type="textarea"
        v-model="replyContent"
        :placeholder="getReplyPlaceholder"
        rows="2"
        style="width: 100%;"
      ></el-input>
      <el-button type="primary" @click="submitReply">提交回复</el-button>
    </div>

    <!-- 渲染子评论 -->
    <div v-if="item.children && item.children.length > 0" class="children-container">
      <comment-item
        v-for="child in item.children"
        :key="child.id"
        :item="child"
        :depth="depth + 1"
        @reply="$emit('reply', child)"
        @delete="$emit('delete', child.id)"
      ></comment-item>
    </div>

  </div>
</template>

<script>
export default {
  name: 'CommentItem',
  props: {
    item: {
      type: Object,
      required: true
    },
    depth: {
      type: Number,
      default: 0
    }

  },
  data() {
    return {
      isReplying: false,
      replyContent: ''
    };
  },
  computed: {
    getReplyPlaceholder() {
      return this.depth === 0
        ? "请输入评论..."
        : `@${this.item.username} 请输入回复...`; // 动态生成占位符
    }
  },
  methods: {
    toggleReply() {
      this.isReplying = !this.isReplying;
      if (this.isReplying) {
        this.replyContent = `@${this.item.username} `; // 添加 @username
      }
    },
    submitReply() {
      if (!this.replyContent.trim()) {
        this.$message({
          message: "回复内容不能为空！",
          type: "warning"
        });
        return;
      }

      this.$emit('reply', {
        content: this.replyContent,
        parentId: this.item.id // 传递当前评论的ID作为父ID
      });

      this.replyContent = '';
      this.isReplying = false; // 隐藏回复输入框
    }
  }
};
</script>

<style scoped>
.comment {
  background: #f5f5f5;
  border: 1px solid #eee;
  border-radius: 5px;
  padding: 10px;
  margin-bottom: 5px;
}


.comment-content {
  padding: 15px;                     /* 内边距 */
  margin-bottom: 10px;               /* 下边距 */
  background: transparent;           /* 透明背景 */
  border: none;
  /* 背景模糊效果 */

}
.reply-container {
  margin-top: 10px;
}

.comment-time {
  color: #888;
  font-size: 12px;
  margin-left: 10px;
}

.children-container {
  margin-left: 20px; /* 子评论的缩进 */
}
</style>
